package com.zyk.leetcode;

import java.util.Arrays;

/**
 * @author zhangsan
 * @date 2021/4/21 15:09
 */
public class C41 {

    // 暴力解
    public static int firstMissingPositive(int[] nums) {
        Arrays.sort(nums);
        int i = 0;
        int pre = 0, next = 1;
        for (; i < nums.length; i++) {
            if (nums[i] <= 0) continue;
            if (nums[i] == pre) continue;
            if (nums[i] == next) {
                next++;
                pre = nums[i];
            } else {
                return next;
            }
        }
        return next;
    }

    public static int firstMissingPositive2(int[] nums) {
        int N = nums.length;
        for (int i = 1; i <= N; i++) {
            if (!binarySearch(nums, i)) return i;
        }
        return N + 1;
    }

    private static boolean binarySearch(int[] nums, int target) {
        int l = 0, r = nums.length - 1, m;
        while (l <= r) {
            m = (l + r) >> 1;
            if (nums[m] == target) {
                return true;
            } else if (nums[m] < target) {
                l = m + 1;
            } else {
                r = m - 1;
            }
        }
        return false;
    }

    // O(N) 空间: O(1)
    public static int firstMissingPositive3(int[] nums) {
        int l = 0, r = nums.length;
        while (l < r) {
            if (nums[l] == l + 1) {
                l++;
            } else if (nums[l] <= l || nums[l] > r || nums[l] == nums[nums[l] - 1]) {
                swap(nums, l, --r);
            } else {
                swap(nums, nums[l] - 1, l);
            }
        }
        return l + 1;
    }

    public static void swap(int[] nums, int a, int b) {
        nums[a] = nums[a] ^ nums[b];
        nums[b] = nums[a] ^ nums[b];
        nums[a] = nums[a] ^ nums[b];
    }

    // for test
    public static void main(String[] args) {
        int[] nums = {3, 4, -1, 1};
//        int[] nums = {1, 2, 0};
//        int[] nums = {7, 8, 9, 11, 12};
        System.out.println(firstMissingPositive(nums));
        System.out.println(firstMissingPositive2(nums));
        System.out.println(firstMissingPositive3(nums));
    }

}
